<?php

namespace App\Services;

use App\Exceptions\ApiException;
use App\Models\TradeProduct;
use App\Services\Base\CacheService;
use App\Services\Coin\BinancePriceService;

class QuotaServices
{

    const MOCK = false;

    /**
     * 获取最新价（根据symbol）
     * @param $symbol
     * @param $throw
     * @return array|int|mixed|string
     * @throws ApiException
     */
    public static function getLast($symbol, $throw = false)
    {
        $quota_symbol = TradeProduct::pair($symbol);
        if (!$quota_symbol) {
            if ($throw) {
                throw new ApiException("价格错误");
            } else {
                return 0;
            }
        }
        $data = CacheService::get("quota:{$quota_symbol}");
        if (!$data) {
            if (self::MOCK) {
                $data = ['price' => 11.2, 'symbol' => $symbol];
            }
        }
        return $data;
    }

    /**
     * 获取最新价（根据行情代码）
     * @param $quota_symbol
     * @return int|mixed
     */
    public static function getLastByQuota($quota_symbol)
    {
        return asMoney(CacheService::get("quota:{$quota_symbol}")['price'] ?? 0, 6);
    }

    /**
     * 获取上一天最新价（根据行情代码）
     * @param $quota_symbol
     * @return int|mixed
     */
    public static function getLastDayByQuota($quota_symbol)
    {
        return asMoney(CacheService::get("quota:{$quota_symbol}:lastday")['price'] ?? 0, 6);
    }

    public static function getUpDown($quota_symbol, $price = 0)
    {
        $last_day_quota = self::getLastDayByQuota($quota_symbol);
        if ($price > 0) {
            $now = $price;
        } else {
            $now = self::getLastByQuota($quota_symbol);
        }

        if ($now == 0) {
            return 0;
        }
        return asMoney(($now - $last_day_quota) / ($last_day_quota ?? $now), 6);
    }

    /**
     * 获取 数字货币/虚拟币行情
     * @param $symbol
     * @return float|int
     */
    public static function getUnitPrice($symbol)
    {
        $price = CacheService::get("price:{$symbol}");
        (is_numeric($price) && $price>0) || ($price = (new BinancePriceService)->getPrice($symbol));
        return is_numeric($price) && $price>0 ? $price: 1;
    }

    /**
     * USD转成币数
     * @param $usd_amount
     * @param $symbol
     * @return false|float|int
     */
    public static function fromUSD($usd_amount, $symbol)
    {
        $price = self::getUnitPrice($symbol);
        return $price > 0 ? $usd_amount / $price : false;
    }

    /**
     * 币数转成USD
     * @param $coin_amount
     * @param $symbol
     * @return float|int
     */
    public static function toUSD($coin_amount, $symbol)
    {
        $price = self::getUnitPrice($symbol);
        return $coin_amount * $price;
    }

}
